/**
 * Description:
 * Class Name:subject1_use_synchronized_method
 * Date:2022/5/19 9:48
 *
 * @author LTisme
 * @version JAVA17
 */
package 疯狂Java讲义.第16章_多线程.课后练习;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

class Thread1 extends Thread{
    private final ReentrantLock lock;
    private final Condition condition;
    private int[] commonTemp;
    public Thread1(String name, ReentrantLock lock, Condition condition, int[] commonTemp){
        super(name);
        this.lock = lock;
        this.condition = condition;
        this.commonTemp = commonTemp;
    }

    @Override
    public void run() {
        for (int i = 1; i <= 52; i++) {
            lock.lock();
            try {
                while (commonTemp[0] % 3 == 0){
                    condition.await();
                }
                System.out.print(i);
                commonTemp[0]++;
                condition.signalAll();
            }
            catch (Exception e){
                e.printStackTrace();
            }
            finally {
                lock.unlock();
            }
        }
    }
}

class Thread2 extends Thread{
    private final ReentrantLock lock;
    private final Condition condition;
    private int[] commonTemp;
    public Thread2(String name, ReentrantLock lock, Condition condition, int[] commonTemp){
        super(name);
        this.lock = lock;
        this.condition = condition;
        this.commonTemp = commonTemp;
    }

    @Override
    public void run() {
        for (char ch = 'A'; ch <= 'Z'; ch++){
            lock.lock();
            try {
                while (commonTemp[0] % 3 != 0){
                    condition.await();
                }
                System.out.print(ch);
                commonTemp[0]++;
                condition.signalAll();
            }
            catch (Exception e){
                e.printStackTrace();
            }
            finally {
                lock.unlock();
            }
        }
    }
}

public class subject1_other_way {
    public static final ReentrantLock lock = new ReentrantLock();
    public static final Condition condition = lock.newCondition();
    public static int[] index = {1};

    public static void main(String[] args) {
        new Thread1("num", lock, condition, index).start();
        new Thread2("char", lock, condition, index).start();
    }
}
